//
//  ViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/8/26.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "ViewController.h"
#import "Masonry.h"
#import "MainViewController.h"
#import "AFNetworking.h"
#import "YXKit.h"
#import "AlarmViewController.h"
#import "NavigationController.h"
#import "TabBarViewController.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"

@interface ViewController ()<UITextFieldDelegate>

@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)UITextField *username;
@property (nonatomic,strong)UITextField *passworld;

@end

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES];
    self.tabBarController.tabBar.hidden = YES;
    [self checkInternetMethod];


}
- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    UIImageView *backImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
    backImage.image = [UIImage imageNamed:@"big_bg"];
    [self.view addSubview:backImage];
    //左上角logo
    UIImageView *leftLogo = [[UIImageView alloc]init];
    leftLogo.image = [UIImage imageNamed:@"logo"];
    [backImage addSubview:leftLogo];
    [leftLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImage).with.offset(20);
        make.top.equalTo(backImage).with.offset(30);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    //右上角logo
    UIImageView *rightLogo = [[UIImageView alloc]init];
    rightLogo.image = [UIImage imageNamed:@"eng_name"];
    [backImage addSubview:rightLogo];
    [rightLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(backImage).with.offset(-20);
        make.top.equalTo(backImage).with.offset(40);
        make.size.mas_equalTo(CGSizeMake(100, 10));
    }];
    //设置用户名和用户密码的背景
    UIView *whiteBKView = [[UIView alloc]init];
    whiteBKView.backgroundColor = [UIColor whiteColor];
    [backImage addSubview:whiteBKView];
    [whiteBKView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(backImage).with.offset(-150);
        make.left.equalTo(backImage).with.offset(25);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-50, self.view.frame.size.height/3));
    }];
    UIImageView *titleBKImageView = [[UIImageView alloc]init];
    titleBKImageView.image = [UIImage imageNamed:@"title_bg"];
    [backImage addSubview:titleBKImageView];
    [titleBKImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backImage).with.offset(25);
        make.bottom.equalTo(whiteBKView.mas_top).with.offset(0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-50, 70));
    }];
    //右边标题
    UIImageView *titleImage = [[UIImageView alloc]init];
    titleImage.image = [UIImage imageNamed:@"title"];
    [titleBKImageView addSubview:titleImage];
    [titleImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleBKImageView).with.offset((self.view.frame.size.width-50)/4);
        make.bottom.equalTo(titleBKImageView).with.offset(-12);
        make.size.mas_equalTo(CGSizeMake((self.view.frame.size.width-50)/4*3-30, 45));
    }];
    //左边锁logo
    UIImageView *lockImageView = [[UIImageView alloc]init];
    lockImageView.image = [UIImage imageNamed:@"img_lock"];
    [titleBKImageView addSubview:lockImageView];
    [lockImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleBKImageView).with.offset(20);
        make.bottom.equalTo(titleBKImageView).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(35, 55));
    }];
    //中间竖线
    UIImageView *lineImageView = [[UIImageView alloc]init];
    lineImageView.image = [UIImage imageNamed:@"line"];
    [titleBKImageView addSubview:lineImageView];
    [lineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(lockImageView.mas_right).with.offset((self.view.frame.size.width/4-55)/4);
        make.bottom.equalTo(titleBKImageView).with.offset(-10);
        make.size.mas_equalTo(CGSizeMake(3, 50));
    }];
    UIImageView *userIcon = [[UIImageView alloc]init];
    userIcon.image = [UIImage imageNamed:@"user"];
    [whiteBKView addSubview:userIcon];
    [userIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBKView).offset(20);
        make.top.equalTo(whiteBKView).offset(20);
        make.size.mas_equalTo(CGSizeMake(30, 33));
    }];
    _username = [[UITextField alloc]init];
    _username.clearButtonMode = UITextFieldViewModeAlways;
    _username.placeholder = @"请输入用户名";
    //_username.text = @"13510944647";
    _username.delegate = self;

    [whiteBKView addSubview:_username];
    [_username mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(userIcon.mas_right).offset(15);
        make.top.equalTo(whiteBKView).offset(25);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-125, 30));
    }];
    //底部黑线
    UIView *line1 = [[UIView alloc]init];
    line1.backgroundColor = [UIColor blackColor];
    [whiteBKView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBKView).offset(20);
        make.top.equalTo(userIcon.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-90, 1));
    }];
    UIImageView *PWIcon = [[UIImageView alloc]init];
    PWIcon.image = [UIImage imageNamed:@"password_icon"];
    [whiteBKView addSubview:PWIcon];
    [PWIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBKView).offset(20);
        make.top.equalTo(line1.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(30, 33));
    }];
    _passworld = [[UITextField alloc]init];
    _passworld.placeholder = @"请输入用户密码";
   // _passworld.text = @"123456";
    _passworld.delegate = self;

    //设置密文
    _passworld.secureTextEntry = YES;
    _passworld.clearButtonMode = UITextFieldViewModeAlways;
    [whiteBKView addSubview:_passworld];
    [_passworld mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(PWIcon.mas_right).offset(15);
        make.top.equalTo(line1.mas_bottom).offset(25);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-125, 30));
    }];
    //底部黑线
    UIView *line2 = [[UIView alloc]init];
    line2.backgroundColor = [UIColor blackColor];
    [whiteBKView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBKView).offset(20);
        make.top.equalTo(PWIcon.mas_bottom).offset(2);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width-90, 1));
    }];
    UIButton *LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [LoginBtn setImage:[UIImage imageNamed:@"loign_button"] forState:UIControlStateNormal];
    [LoginBtn addTarget:self action:@selector(LoginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [whiteBKView addSubview:LoginBtn];
    [LoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(whiteBKView).offset((self.view.frame.size.width-50)/3-10);
        make.top.equalTo(line2.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake((self.view.frame.size.width-50)/3+20, 35));
    }];
    //打开手势交互
    whiteBKView.userInteractionEnabled = YES;
    backImage.userInteractionEnabled = YES;
    

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(kbHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
/* 键盘显示*/
- (void)kbShow:(NSNotification *)sender
{
    
    NSDictionary *info = [sender userInfo];
    //    NSLog(@"shurufa--------------%@",info);
    CGRect kbrect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGRect frame = self.view.frame;
    CGFloat exten_x = _username.frame.origin.y - 100 < kbrect.size.height ? _username.frame.origin.y - 100 : kbrect.size.height;
    
    
    frame = CGRectMake(0,exten_x, frame.size.width, frame.size.height);
    self.view.frame = frame;
}
/*键盘隐藏*/
- (void)kbHidden:(NSNotification *)sender
{
    
   // NSDictionary *info = [sender userInfo];
    //    NSLog(@"shurufa--------------%@",info);
    CGRect frame = self.view.frame;
    
    frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
    self.view.frame = frame;
    
}
//判断网络
- (void)checkInternetMethod{
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status ==AFNetworkReachabilityStatusReachableViaWWAN) {
            NSSLog(@"网络连接正常");
            
        }else{
            //_interError = @"网络异常";
            [self showAlert:@"温馨提示" message:@"请检查您的网络" actionWithTitle:@"我知道了"];
        }
    }];
}

//登录按钮点击事件
- (void)LoginBtnClick{
    
    NSLog(@"登陆被点击");
   if (self.username.text.length == 0 || self.passworld.text.length == 0) {

       [[YXAlertHUD stateHUDWithHUDTyep:1 message:@"账户密码不能为空" textColor:[UIColor redColor] iconColor:[UIColor redColor]] show];
       
   }else{
       MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
       //请求超时时间设置
       self.manager.requestSerializer.timeoutInterval = 15;

        [_manager POST:K_Login parameters:@{userName:self.username.text,passWord:self.passworld.text} progress:^(NSProgress * _Nonnull uploadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSInteger status = [dic[@"status"]integerValue];
            //用户id
            NSInteger userID = [dic[@"data"][@"user"][@"id"]
                                integerValue];
            //用户名
            NSString *username = dic[@"data"][@"user"][@"name"];
            //帐户名
            NSString *loginAcc = dic[@"data"][@"user"][@"loginAcc"];
            //电话号码
            NSString *tel = dic[@"data"][@"user"][@"tel"];
            //用户等级
            NSInteger lev = [dic[@"data"][@"user"][@"level"]
                             integerValue];
            //用户等级名称
            NSString *levelN = dic[@"data"][@"user"][@"levelName"];
            //头像url
            NSString *iconUrl = dic[@"data"][@"user"][@"pic"];
            //判断权限等级
            NSInteger upper = [dic[@"data"][@"user"][@"upper"]integerValue];
            NSLog(@"%ld",status);
            //邮箱账户
            NSString *emailStr = dic[@"data"][@"user"][@"email"];
            NSArray *menuList = dic[@"data"][@"user"][@"menuList"];

            if (status == 1) {

                
                //1.找到UIApplication对象
                //表示当前正在运行的应用程序
                UIApplication *app = [UIApplication sharedApplication];
                //2.获取代理对象
                AppDelegate *delegate = app.delegate;
                //3.将数据保存到username属性中
                delegate.userId = userID;
                delegate.username = username;
                delegate.loginName = loginAcc;
                delegate.tel = tel;
                delegate.level = lev;
                delegate.levelName = levelN;
                delegate.iconUrl = iconUrl;
                delegate.upper = upper;
                delegate.email = emailStr;
                delegate.List = menuList;
                //延时操作
                [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                    
                    [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"登录成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                    
                } completion:^(BOOL finished) {
                    
                    TabBarViewController *tab = [[TabBarViewController alloc]init];
                    
                    [self presentViewController:tab animated:NO completion:nil];
                    
                    
                }];

                //2.字典写入文件
                NSDictionary *dic = @{@"username":_username.text,@"password":_passworld.text,@"list":menuList,@"userid":[NSString stringWithFormat:@"%ld",userID],@"level":[NSString stringWithFormat:@"%ld",lev],@"loginAcc":loginAcc,@"tel":tel,@"levelN":levelN,@"iconurl":iconUrl,@"upper":[NSString stringWithFormat:@"%ld",upper],@"emailStr":emailStr};
                [dic writeToFile:[self filePath] atomically:YES];
            }else{
            
                [[YXAlertHUD stateHUDWithHUDTyep:1 message:@"账户或密码不正确" textColor:[UIColor redColor] iconColor:[UIColor redColor]] show];
            }
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
            NSInteger status = responses.statusCode;
            //        NSSLog(@"%ld",(long)responses.statusCode);
            if (status >=500 || status == 0) {
                [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
            }else{
                [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
            }
        }];
    }

}
//获取文件路径
- (NSString *)filePath{
    //1.获取Document(存放持久保存的数据)文件夹路径
    //参数1:查找的文件路径
    //参数2:在那个域中查找
    //参数3:是否显示详细路径
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //NSLog(@"%@",filtPath);
    return filtPath;
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
@end
